package org.jeecg.common.util.security;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.util.encoders.Base64;
import org.jeecg.common.util.SM2Utils;
import org.jeecg.common.util.SM4Utils;
import org.jeecg.common.util.security.entity.*;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @Description: SecurityTools
 * @author: jeecg-boot
 */
public class SecurityTools {
    public static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    public static SecurityResp valid(SecurityReq req) {
        SecurityResp resp = new SecurityResp();
        String pubKey = req.getPubKey();
        String aesKey = req.getAesKey();
        String data = req.getData();
        String signData = req.getSignData();
        RSA rsa = new RSA(null, Base64Decoder.decode(pubKey));
        Sign sign = new Sign(SignAlgorithm.SHA1withRSA, null, pubKey);


        byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey);
        //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes));
        AES aes = SecureUtil.aes(decryptAes);

        String dencrptValue = aes.decryptStr(data);
        //log.info("解密后报文"+dencrptValue);
        resp.setData(JSONObject.parseObject(dencrptValue));

        boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData));
        resp.setSuccess(verify);
        return resp;
    }

    public static SecuritySignResp sign(SecuritySignReq req) {
        SecretKey secretKey = SecureUtil.generateKey(ALGORITHM);
        byte[] key = secretKey.getEncoded();
        String prikey = req.getPrikey();
        String data = req.getData();

        AES aes = SecureUtil.aes(key);
        aes.getSecretKey().getEncoded();
        String encrptData = aes.encryptBase64(data);
        RSA rsa = new RSA(prikey, null);
        byte[] encryptAesKey = rsa.encrypt(secretKey.getEncoded(), KeyType.PrivateKey);
        //log.info(("rsa加密过的秘钥=="+Base64Encoder.encode(encryptAesKey));

        Sign sign = new Sign(SignAlgorithm.SHA1withRSA, prikey, null);
        byte[] signed = sign.sign(data.getBytes());

        //log.info(("签名数据===》》"+Base64Encoder.encode(signed));

        SecuritySignResp resp = new SecuritySignResp();
        resp.setAesKey(Base64Encoder.encode(encryptAesKey));
        resp.setData(encrptData);
        resp.setSignData(Base64Encoder.encode(signed));
        return resp;
    }

    public static MyKeyPair generateKeyPair() {
        KeyPair keyPair = SecureUtil.generateKeyPair(SignAlgorithm.SHA1withRSA.getValue(), 2048);
        String priKey = Base64Encoder.encode(keyPair.getPrivate().getEncoded());
        String pubkey = Base64Encoder.encode(keyPair.getPublic().getEncoded());
        MyKeyPair resp = new MyKeyPair();
        resp.setPriKey(priKey);
        resp.setPubKey(pubkey);
        return resp;
    }
    public static void main(String[] args) {
        try {
            // 1. 生成密钥对
        /*    KeyPair keyPair = SM2Utils.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            // 2. 转换为 Base64 存储或传输
            String publicKeyBase64 = SM2Utils.publicKeyToBase64(publicKey);
            String privateKeyBase64 = SM2Utils.privateKeyToBase64(privateKey);
            System.out.println("公钥(Base64): " + publicKeyBase64);
            System.out.println("私钥(Base64): " + privateKeyBase64);*/
            String publicKeyBase64="MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE781mzatEPKHmVA15dWZKy+It3ko5KOh7pf3C/5MkszYGbdjMXUrrts9ZyYoHvFk65TkpFxThSBdQOLxaiGgZdg==\n";
            String privateKeyBase64="MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQglEWzjO6ZLGEXHAGAgmTc1SDAWmHexwSet45XVTzKYhygCgYIKoEcz1UBgi2hRANCAATvzWbNq0Q8oeZUDXl1ZkrL4i3eSjko6Hul/cL/kySzNgZt2MxdSuu2z1nJige8WTrlOSkXFOFIF1A4vFqIaBl2\n";
            // 3. 从 Base64 恢复密钥
            PublicKey restoredPublicKey = SM2Utils.base64ToPublicKey(publicKeyBase64);
            PrivateKey restoredPrivateKey = SM2Utils.base64ToPrivateKey(privateKeyBase64);

            // 4. 加密和解密示例
            String plainText = "754cf1d817ed40c69ad61269e9401438";
            String encrypted = SM2Utils.encrypt(plainText, restoredPublicKey);
            Base64.decode(encrypted);
            String hex = Hex.encodeHexString(Base64.decode(encrypted)).toUpperCase(); // 转十六进制（大写）
            System.out.println(hex);
            System.out.println("加密后base64: " + encrypted);
            System.out.println("加密后16进制: " + hex);
            //System.out.println("加密后: " + Base64.toBase64String(restoredPublicKey.getEncoded()));

            String decrypted = SM2Utils.decrypt(encrypted, restoredPrivateKey);
            System.out.println("解密后: " + decrypted);




        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
